package com.weai.service.impl;

import com.weai.dto.AuthResponse;
import com.weai.dto.LoginRequest;
import com.weai.dto.RegisterRequest;
import com.weai.dto.UserDTO;
import com.weai.entity.User;
import com.weai.exception.ResourceNotFoundException;
import com.weai.exception.UserAlreadyExistsException;
import com.weai.repository.UserRepository;
import com.weai.service.UserService;
import com.weai.util.JwtUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户服务实现类
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class UserServiceImpl implements UserService {
    
    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;
    private final AuthenticationManager authenticationManager;
    private final UserDetailsService userDetailsService;
    private final JwtUtil jwtUtil;
    
    /**
     * 注册新用户
     *
     * @param request 注册请求
     * @return 认证响应（包含令牌和用户信息）
     */
    @Override
    @Transactional
    public AuthResponse register(RegisterRequest request) {
        log.info("开始注册新用户: {}", request.getEnglishName());
        
        // 检查用户名是否已存在
        if (userRepository.existsByEnglishName(request.getEnglishName())) {
            log.warn("用户名已存在: {}", request.getEnglishName());
            throw new UserAlreadyExistsException("用户名已存在");
        }
        
        // 创建新用户
        User user = new User();
        user.setChineseName(request.getChineseName());
        user.setEnglishName(request.getEnglishName());
        user.setPassword(passwordEncoder.encode(request.getPassword()));
        user.setRole(request.getRole());
        user.setCreateTime(LocalDateTime.now());
        user.setLastLoginTime(LocalDateTime.now());
        
        User savedUser = userRepository.save(user);
        log.info("新用户注册成功: {}", savedUser.getEnglishName());
        
        // 生成JWT令牌
        UserDetails userDetails = userDetailsService.loadUserByUsername(request.getEnglishName());
        String token = jwtUtil.generateToken(userDetails);
        
        return new AuthResponse(token, toDto(savedUser));
    }
    
    /**
     * 用户登录
     *
     * @param request 登录请求
     * @return 认证响应（包含令牌和用户信息）
     */
    @Override
    @Transactional
    public AuthResponse login(LoginRequest request) {
        log.info("用户登录: {}", request.getEnglishName());
        
        // 验证用户凭据
        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(request.getEnglishName(), request.getPassword())
        );
        
        // 更新最后登录时间
        User user = userRepository.findByEnglishName(request.getEnglishName())
                .orElseThrow(() -> new ResourceNotFoundException("用户不存在"));
        user.setLastLoginTime(LocalDateTime.now());
        User updatedUser = userRepository.save(user);
        log.info("用户登录成功: {}", updatedUser.getEnglishName());
        
        // 生成JWT令牌
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        String token = jwtUtil.generateToken(userDetails);
        
        return new AuthResponse(token, toDto(updatedUser));
    }
    
    /**
     * 获取所有用户
     *
     * @return 用户列表
     */
    @Override
    @Transactional(readOnly = true)
    public List<UserDTO> findAll() {
        log.info("获取所有用户");
        return userRepository.findAll().stream()
                .map(this::toDto)
                .collect(Collectors.toList());
    }
    
    /**
     * 根据ID查找用户
     *
     * @param id 用户ID
     * @return 用户DTO
     */
    @Override
    @Transactional(readOnly = true)
    public UserDTO findById(Long id) {
        log.info("根据ID查找用户: {}", id);
        return userRepository.findById(id)
                .map(this::toDto)
                .orElseThrow(() -> new ResourceNotFoundException("用户不存在"));
    }
    
    /**
     * 根据英文名查找用户
     *
     * @param englishName 英文名
     * @return 用户DTO
     */
    @Override
    @Transactional(readOnly = true)
    public UserDTO findByEnglishName(String englishName) {
        log.info("根据英文名查找用户: {}", englishName);
        return userRepository.findByEnglishName(englishName)
                .map(this::toDto)
                .orElseThrow(() -> new ResourceNotFoundException("用户不存在"));
    }
    
    /**
     * 更新用户信息
     *
     * @param id      用户ID
     * @param userDTO 用户DTO
     * @return 更新后的用户DTO
     */
    @Override
    @Transactional
    public UserDTO update(Long id, UserDTO userDTO) {
        log.info("更新用户信息: {}", id);
        
        User user = userRepository.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("用户不存在"));
        
        // 如果要更改英文名，检查新的英文名是否已存在
        if (!user.getEnglishName().equals(userDTO.getEnglishName()) &&
                userRepository.existsByEnglishName(userDTO.getEnglishName())) {
            log.warn("用户名已存在: {}", userDTO.getEnglishName());
            throw new UserAlreadyExistsException("用户名已存在");
        }
        
        // 更新用户信息
        user.setChineseName(userDTO.getChineseName());
        user.setEnglishName(userDTO.getEnglishName());
        user.setRole(userDTO.getRole());
        
        User updatedUser = userRepository.save(user);
        log.info("用户信息更新成功: {}", updatedUser.getId());
        
        return toDto(updatedUser);
    }
    
    /**
     * 删除用户
     *
     * @param id 用户ID
     */
    @Override
    @Transactional
    public void delete(Long id) {
        log.info("删除用户: {}", id);
        
        if (!userRepository.existsById(id)) {
            throw new ResourceNotFoundException("用户不存在");
        }
        
        userRepository.deleteById(id);
        log.info("用户删除成功: {}", id);
    }
    
    /**
     * 获取所有用户的英文名和中文名
     *
     * @return 用户名称列表，格式为englishName/chineseName
     */
    @Override
    @Transactional(readOnly = true)
    public List<String> findAllUserNames() {
        log.info("获取所有用户的英文名和中文名");
        return userRepository.findAll().stream()
                .map(user -> user.getEnglishName() + "/" + user.getChineseName())
                .collect(Collectors.toList());
    }
    
    /**
     * 将用户实体转换为DTO
     *
     * @param user 用户实体
     * @return 用户DTO
     */
    @Override
    public UserDTO toDto(User user) {
        if (user == null) {
            return null;
        }
        
        UserDTO userDTO = new UserDTO();
        userDTO.setId(user.getId());
        userDTO.setChineseName(user.getChineseName());
        userDTO.setEnglishName(user.getEnglishName());
        userDTO.setRole(user.getRole());
        userDTO.setCreateTime(user.getCreateTime());
        userDTO.setLastLoginTime(user.getLastLoginTime());
        
        return userDTO;
    }
    
    /**
     * 将DTO转换为用户实体
     *
     * @param userDTO 用户DTO
     * @return 用户实体
     */
    @Override
    public User toEntity(UserDTO userDTO) {
        if (userDTO == null) {
            return null;
        }
        
        User user = new User();
        user.setId(userDTO.getId());
        user.setChineseName(userDTO.getChineseName());
        user.setEnglishName(userDTO.getEnglishName());
        user.setRole(userDTO.getRole());
        user.setCreateTime(userDTO.getCreateTime());
        user.setLastLoginTime(userDTO.getLastLoginTime());
        
        return user;
    }
} 